package cc.chinagps.gateway.client;


import cc.chinagps.gateway.client.session.ISession;
import cc.chinagps.gateway.common.Constant;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class MsgSNManager {
    short sn = 0;
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);

    private MsgSNManager() {
    }

    private static class SingletonHolder {
        private static final MsgSNManager INSTANCE = new MsgSNManager();
    }

    public static final MsgSNManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public short getSn() {
        lock.writeLock().lock();
        try {
            if (sn == Short.MAX_VALUE) {
                sn = 1;
            } else {
                sn++;
            }
            return sn;
        } finally {
            lock.writeLock().unlock();
        }
    }

    public short getSn(ISession session) {
        synchronized (session) {
            Object obj = session.getAttribute(Constant.SESSION_KEY_SN);
            Short v;
            if (obj == null) {
                v = 1;
            } else {
                v = (Short) obj;
                if (v >= Short.MAX_VALUE) {
                    v = 1;
                } else {
                    v++;
                }
            }
            session.setAttribute(Constant.SESSION_KEY_SN, v);
            return v;
        }
    }
}
